#ifndef __HTTP_SOCKET_H__
#define __HTTP_SOCKET_H__

#include <stdint.h>

typedef struct ssl_st*  SSL_PTR;

class HttpSocket {
public:
	enum { PORT_HTTP = 80, PORT_HTTPS = 443 };
public:
	HttpSocket();
	~HttpSocket();
	// @input: in millisecond
	int SetTimeout(int recvtime,int sendtime,int conntime);
	// @input: both are in host byte order
	int SetPeer(uint32_t addr, uint16_t port=PORT_HTTP, bool ssl=false);
	int Connect();
	int Disconnect();
	bool IsConnected() const { return m_connected; }

	int SendRequest(const char *pReqHeader, int nHeaderLen,
		const char *pReqData, int nDataLen);
	int RecvResponse(char *pRcvDataBuf, int nRcvBufLen);
	int RecvProtoHeader(char *pRcvDataBuf, int nRcvBufLen);
	int RecvLine(char *pRcvDataBuf, int nRcvBufLen);
	// @output: both are in host byte order
	uint32_t GetPeerAddr() const { return m_peer.addr; }
	uint16_t GetPeerPort() const { return m_peer.port; };
private:
	int   m_socket;
	/*addr to connect*/
	struct _addr {
		uint32_t addr;
		uint16_t port;
	} m_peer;
	bool  m_connected;

	int m_rdtimeo;
	int m_wrtimeo;
	int m_conntimeo;

	/*structures for https--using openssl*/
	SSL_PTR m_ssl;
	bool m_usessl;

private:
	int NewSession();
	int WriteWithSSL(const char *pDataBuf, int nBufLen);
	int ReadWithSSL(char *pDataBuf, int nBufLen);
	int Write(const char *pDataBuf, int nBufLen);
	int Read(char *pDataBuf, int nBufLen);
	int ReadLine(char *pDataBuf, int nBufLen);
	int ReadLineSSL(char *pDataBuf, int nBufLen);
	int ReadProtoHeader(char *pDataBuf, int nBufLen);
	int ReadProtoHeaderSSL(char *pDataBuf, int nBufLen);
	int DoConnect();
	int DoSetTimeout();
};

#endif //__HTTP_SOCKET_H__
